package com.neteast.androidclient.contact.util;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.neteast.androidclient.contact.domain.Contact;
import com.neteast.androidclient.contact.domain.ContactData;

public class JsonUtil {
	
	/**
	 * 将Contact对象转换成json字符串
	 * @return
	 * @throws JSONException 
	 */
	public static JSONObject translateContactToJson(Contact contact) throws JSONException {
		JSONObject object=null;
		if (contact==null) {
			return object;
		}
		object=new JSONObject();
		object.put("ownId", contact.ownId);
		object.put("contactId", JSONObject.NULL);
		object.put("displayName", contact.displayName);
		object.put("nickName", contact.nickName);
		object.put("isReadOnly", contact.isReadOnly?1:0);
		object.put("organization", contact.organization);
		object.put("job", contact.job);
		object.put("photo", contact.photo);
		object.put("hasPhoto", contact.hasPhoto?1:0);
		object.put("sortKey", Character.toString(contact.sortKey));
		object.put("remark", contact.remark);
		object.put("state", contact.state);
		if (!contact.phones.isEmpty()) {
			object.put("phones", populateContactData(contact.phones));
		}
		if (!contact.emails.isEmpty()) {
			object.put("emails", populateContactData(contact.emails));
		}
		if (!contact.ims.isEmpty()) {
			object.put("ims", populateContactData(contact.ims));
		}
		if (!contact.locations.isEmpty()) {
			object.put("locations", populateContactData(contact.locations));
		}
		return object;
	}

	private static JSONArray populateContactData(ArrayList<ContactData> datas)throws JSONException {
		JSONArray arr=new JSONArray();
		for (ContactData data : datas) {
			JSONObject obj=new JSONObject();
			obj.put("label", data.label);
			obj.put("content", data.content);
			obj.put("isReadOnly", data.isReadOnly?1:0);
			obj.put("modified", data.modified);
			obj.put("mimeTypeId", data.mimeTypeId);
			arr.put(obj);
		}
		return arr;
	}
}
